package com.matrix.basecore.net

import android.util.Log
import com.matrix.basecore.constant.Constant
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object RetrofitBuilder {

    private lateinit var mRetrofit: Retrofit
    private const val TAG = "RetrofitBuilder"

    fun initRetrofit(): RetrofitBuilder {
        mRetrofit = Retrofit.Builder()
            .baseUrl(Constant.WallpaperBaseUrl)
            .client(initClient())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        return this
    }

    private fun initClient(): OkHttpClient {
        return OkHttpClient.Builder()
            .callTimeout(10, TimeUnit.SECONDS)
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .followRedirects(false)
            .addInterceptor(HttpLoggingInterceptor { message ->
                Log.i(TAG, message)
            }
                .setLevel(HttpLoggingInterceptor.Level.BODY))
            .build()
    }

    /**
     * 获取请求service
     */
    fun <T> getService(serviceClass: Class<T>): T {
        if (mRetrofit == null) {
            throw UninitializedPropertyAccessException("Retrofit必须初始化")
        } else {
            return mRetrofit!!.create(serviceClass)
        }
    }
}